package com.iemes.controller.work_plan;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.inject.Inject;
import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.iemes.annotation.SystemLog;
import com.iemes.controller.index.BaseController;
import com.iemes.entity.ItemBomFormMap;
import com.iemes.entity.ItemFormMap;
import com.iemes.entity.ProcessWorkFlowFormMap;
import com.iemes.entity.ShopOrderSfcFormMap;
import com.iemes.entity.ShoporderFormMap;
import com.iemes.entity.ShoporderStatusChangeHisoryFormMap;
import com.iemes.exception.BusinessException;
import com.iemes.mapper.WorkPlan.ShoporderMapper;
import com.iemes.mapper.base.BaseMapper;
import com.iemes.service.CommonService;
import com.iemes.service.work_plan.ShoporderMaintenanceService;
import com.iemes.util.Common;
import com.iemes.util.DateUtils;
import com.iemes.util.ListUtils;
import com.iemes.util.ResponseHelp;
import com.iemes.util.ShiroSecurityHelper;

/**
 * 
 */
@Controller
@RequestMapping("/work_plan/shoporder_maintenance/")
public class ShoporderMaintenanceController extends BaseController {

	@Inject
	private BaseMapper baseMapper;

	@Inject
	private ShoporderMapper shoporderMapper;

	@Inject
	private CommonService commonService;

	@Inject
	private ShoporderMaintenanceService shoporderMaintenanceService;

	private Logger log = Logger.getLogger(this.getClass());
	private String shoporderMaintenanceUrl = Common.BACKGROUND_PATH
			+ "/work_plan/shoporder_maintenance/shoporder_maintenance";
	private String uDefinedDataType = "shop_order_maintenance";
	
	private static String NORMAL = "normal";

	// 页面跳转
	@RequestMapping("shoporder_maintenance")
	public String Get_shoporder_maintenance_Url(Model model,HttpServletRequest request) throws Exception {
		model.addAttribute("res", findByRes());
		setShoporderStatusList(model);
		setSfcStatusList(model);
		model.addAttribute("dataKeys", getUDefinedDataField(uDefinedDataType));
		handlePageRes(model,request);
		return shoporderMaintenanceUrl;
	}

	protected void setShoporderStatusList(Model model) {
		Map<String, String> map = new HashMap<String, String>();
		int[] statusArray = new int[] { 0, 1, 2, 3, 4, 5, 6 };
		for (int status : statusArray) {
			map.put(String.valueOf(status), commonService.getShoporderStatusStr(status));
		}
		model.addAttribute("shoporderStatusList", map);
	}

	private int getShoporderStatusBeforeHangup(String shoporderId) {
		ShoporderStatusChangeHisoryFormMap shoporderStatusChangeHisoryFormMap = new ShoporderStatusChangeHisoryFormMap();
		shoporderStatusChangeHisoryFormMap.put("shoporder_id", shoporderId);
		shoporderStatusChangeHisoryFormMap.put("orderby", " order by shoporder_status_change_time desc");
		List<ShoporderStatusChangeHisoryFormMap> listShoporderStatusChangeHisoryFormMap = baseMapper
				.findByNames(shoporderStatusChangeHisoryFormMap);
		if (ListUtils.isNotNull(listShoporderStatusChangeHisoryFormMap)) {
			shoporderStatusChangeHisoryFormMap = listShoporderStatusChangeHisoryFormMap.get(0);
			int shoporderStattusBeforeHangup = shoporderStatusChangeHisoryFormMap
					.getInt("shoporder_status_before_change");
			return shoporderStattusBeforeHangup;
		} else {
			return -9999;
		}
	}
	
	/**
	 * 获取工单的状态列表
	 * @param model
	 */
	private void setShopOrderHistoryStatusList(Model model) {
		Map<String, String> map = new HashMap<String, String>();
		int[] statusArray = new int[] {0,1,2,3,4,5,6};
		for (int status : statusArray) {
			map.put(String.valueOf(status), commonService.getShoporderStatusStr(status));
		}
		model.addAttribute("shopOrderHistoryStatusList", map);
	}

	private void setShoporderStatusList(Model model, int currentShopoderStatus, String shoporderId) {
		/*
		 * 工单状态：0、创建；1、已下达；2、生产中；3、已完成；4、关闭；5、挂起；6、删除 0 允许到4,5 1 允许到4,5 2 允许到4,5 3 不允许调整
		 * 4 不允许调整 5 允许恢复到挂起前的状态
		 */
		Map<String, String> map = new HashMap<String, String>();
		if (currentShopoderStatus == 0 || currentShopoderStatus == 1 || currentShopoderStatus == 2) {
			int[] statusArray = new int[] { currentShopoderStatus, 4, 5 };
			for (int status : statusArray) {
				map.put(String.valueOf(status), commonService.getShoporderStatusStr(status));
			}
		} else if (currentShopoderStatus == 3 || currentShopoderStatus == 4) {
			int[] statusArray = new int[] { currentShopoderStatus };
			for (int status : statusArray) {
				map.put(String.valueOf(status), commonService.getShoporderStatusStr(status));
			}
		} else if (currentShopoderStatus == 5) {
			int shoporderStattusBeforeHangup = getShoporderStatusBeforeHangup(shoporderId);
			if (shoporderStattusBeforeHangup >= -1) {
				int[] statusArray = new int[] { currentShopoderStatus, shoporderStattusBeforeHangup };
				for (int status : statusArray) {
					map.put(String.valueOf(status), commonService.getShoporderStatusStr(status));
				}
			} else {
				int[] statusArray = new int[] { currentShopoderStatus };
				for (int status : statusArray) {
					map.put(String.valueOf(status), commonService.getShoporderStatusStr(status));
				}
			}
		}
		model.addAttribute("shoporderStatusList", map);
	}

	private void setSfcStatusList(Model model) {
		Map<String, String> map = new HashMap<String, String>();
		int[] statusArray = new int[] { 0, 1, 2, 3, 4 };
		for (int status : statusArray) {
			map.put(String.valueOf(status), commonService.getSfcStatusStr(status));
		}
		model.addAttribute("sfcStatusList", map);
	}

	/**
	 * 保存工单信息
	 * 
	 * @return
	 */
	@ResponseBody
	@RequestMapping("saveShoporder")
	@SystemLog(module = "工单维护", methods = "工单维护-保存工单") // 凡需要处理业务逻辑的.都需要记录操作日志
	public String saveShoporder() {
		ShoporderFormMap shoporderFormMap = getFormMap(ShoporderFormMap.class);
		shoporderFormMap.put("create_time", DateUtils.getStringDateTime());
		shoporderFormMap.put("create_user", ShiroSecurityHelper.getCurrentUsername());
		shoporderFormMap.put("site_id", ShiroSecurityHelper.getSiteId());
		shoporderFormMap.put("shoporder_type", this.NORMAL);

		try {
			String shoporderId = shoporderFormMap.getStr("id");
			int shoporderStattusBeforeHangup = -9999;
			if (!StringUtils.isEmpty(shoporderId)) {
				shoporderStattusBeforeHangup = getShoporderStatusBeforeHangup(shoporderId);
			}
			shoporderMaintenanceService.saveShoporder(shoporderFormMap, shoporderStattusBeforeHangup);
			String baseInfoUpdateMsg = shoporderFormMap.getStr("baseInfoUpdateMsg");
			if(!StringUtils.isEmpty(baseInfoUpdateMsg)) {
				return ResponseHelp.responseErrorText(baseInfoUpdateMsg);
			}
		} catch (BusinessException e) {
			log.error(e.getMessage());
			return ResponseHelp.responseErrorText(e.getMessage());
		}
		return ResponseHelp.responseText();
	}

	/**
	 * 检索工单信息
	 * 
	 * @param model
	 * @param request
	 * @return
	 */
	@RequestMapping("queryShoporder")
	public String queryShoporder(Model model, HttpServletRequest request) {
		String siteId = ShiroSecurityHelper.getSiteId();
		String shoporderNo = request.getParameter("shoporder_no");
		// 1.查询工单的基本信息
		ShoporderFormMap shoporderFormMap = new ShoporderFormMap();
		shoporderFormMap.put("shoporder_no", shoporderNo);
		shoporderFormMap.put("site_id", siteId);
		List<ShoporderFormMap> listShoporderFormMap = baseMapper.findByNames(shoporderFormMap);
		if (!ListUtils.isNotNull(listShoporderFormMap)) {
			String errMessage = "未检索到工单编号为：" + shoporderNo.toUpperCase() + "的信息";
			log.error(errMessage);
			model.addAttribute("res", findByRes());
			setShoporderStatusList(model);
			setSfcStatusList(model);
			model.addAttribute("dataKeys", getUDefinedDataField(uDefinedDataType));
			model.addAttribute("errorMessage", errMessage);
			handlePageRes(model,request);
			return shoporderMaintenanceUrl;
		}
		shoporderFormMap = listShoporderFormMap.get(0);

		// 2.查询物料信息和物料清单信息
		String itemId = shoporderFormMap.getStr("shoporder_item_id");
		queryItemAndItemBom(model, itemId);

		// 3.查询工艺路线信息
		String processWorkflowId = shoporderFormMap.getStr("process_workflow_id");
		queryProcessWorkflow(model, processWorkflowId);

		// 4.查询工单下达数量和完成数量
		queryShoporderProductionNumber(shoporderFormMap);

		// 6.查询自定义数据
		String shoporderId = shoporderFormMap.getStr("id");
		getUDefinedDataValue(model, shoporderId, uDefinedDataType, "dataKeys");

		// 7.查询状态调整的历史记录
		queryShoporderStatusChangeHistory(model, shoporderId);

		// 8.查询sfc列表
		queryShoporderSfcList(model,shoporderId);

		int shoporderStatus = shoporderFormMap.getInt("status");
		setShoporderStatusList(model, shoporderStatus, shoporderId);
		setShopOrderHistoryStatusList(model);
		setSfcStatusList(model);
		model.addAttribute("shoporderFormMap", shoporderFormMap);
		model.addAttribute("successMessage", "检索成功");
		handlePageRes(model,request);
		return shoporderMaintenanceUrl;
	}

	public void queryItemAndItemBom(Model model, String itemId) {
		// 查物料
		ItemFormMap itemFormMap = new ItemFormMap();
		itemFormMap.put("id", itemId);
		List<ItemFormMap> listItemFormMap = baseMapper.findByNames(itemFormMap);

		if (!ListUtils.isNotNull(listItemFormMap)) {
			log.error("未检索到工单的物料信息");
			model.addAttribute("errorMessage", "未检索到工单的物料信息");
			return;
		}
		ItemFormMap itemFormMap2 = listItemFormMap.get(0);
		model.addAttribute("itemFormMap", itemFormMap2);

		// 查物料清单
		String bomId = itemFormMap2.getStr("bom_no");
		if (!StringUtils.isEmpty(bomId)) {
			List<ItemBomFormMap> itemBomFormMapList = baseMapper.findByAttribute("id", bomId, ItemBomFormMap.class);
			if (ListUtils.isNotNull(itemBomFormMapList)) {
				ItemBomFormMap itemBomFormMap = itemBomFormMapList.get(0);
				model.addAttribute("itemBomFormMap", itemBomFormMap);
			}
		}
	}

	public void queryProcessWorkflow(Model model, String workflowId) {
		// 查工艺路线
		ProcessWorkFlowFormMap processWorkFlowFormMap = new ProcessWorkFlowFormMap();
		processWorkFlowFormMap.put("id", workflowId);
		List<ProcessWorkFlowFormMap> listProcessWorkFlowFormMap = baseMapper.findByNames(processWorkFlowFormMap);

		if (!ListUtils.isNotNull(listProcessWorkFlowFormMap)) {
			log.error("未检索到工单的工艺路线信息");
			model.addAttribute("errorMessage", "未检索到工单的工艺路线信息");
			return;
		}
		processWorkFlowFormMap = listProcessWorkFlowFormMap.get(0);
		model.addAttribute("processWorkFlowFormMap", processWorkFlowFormMap);
	}

	public void queryShoporderProductionNumber(ShoporderFormMap shoporderFormMap) {
		// 查询工单生产数量(包括完成数量和报废数量)
		int completedNumber = 0;
		int scrapNumber = 0;
		String shoporderId = shoporderFormMap.getStr("id");
		ShopOrderSfcFormMap shopOrderSfcFormMap = new ShopOrderSfcFormMap();
		shopOrderSfcFormMap.put("shoporder_id", shoporderId);
		List<ShopOrderSfcFormMap> listShopOrderSfcFormMap = baseMapper.findByNames(shopOrderSfcFormMap);
		if (!ListUtils.isNotNull(listShopOrderSfcFormMap)) {
			completedNumber = 0;
			scrapNumber = 0;
		} else {
			for (int i = 0; i < listShopOrderSfcFormMap.size(); i++) {
				ShopOrderSfcFormMap map = listShopOrderSfcFormMap.get(0);
				int sfcStatus = map.getInt("sfc_status");
				if (sfcStatus == 2) {
					completedNumber++;
				} else if (sfcStatus == 3) {
					scrapNumber++;
				}
			}
		}
		shoporderFormMap.put("completed_number", completedNumber);
		shoporderFormMap.put("scrap_number", scrapNumber);
	}

	public void queryShoporderStatusChangeHistory(Model model, String shoporderId) {
		ShoporderStatusChangeHisoryFormMap shoporderStatusChangeHisoryFormMap = new ShoporderStatusChangeHisoryFormMap();
		shoporderStatusChangeHisoryFormMap.put("shoporder_id", shoporderId);
		shoporderStatusChangeHisoryFormMap.put("orderby", " order by shoporder_status_change_time desc");
		List<ShoporderStatusChangeHisoryFormMap> listShoporderStatusChangeHisoryFormMap = baseMapper
				.findByNames(shoporderStatusChangeHisoryFormMap);
		if (ListUtils.isNotNull(listShoporderStatusChangeHisoryFormMap)) {
			model.addAttribute("shoporderStatusChangeHistoryList", listShoporderStatusChangeHisoryFormMap);
		}
	}

	public void queryShoporderSfcList(Model model, String shoporderId) {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("shoporderId", shoporderId);
		try {
			List<Map<String, Object> > listShopOrderSfcFormMap = shoporderMapper.getShoporderSfcList(map);
			if (ListUtils.isNotNull(listShopOrderSfcFormMap)) {
				model.addAttribute("shoporderSfcList", listShopOrderSfcFormMap);
			}
			
		} catch (Exception e) {
			throw new BusinessException(e.getMessage());
		}

	}

	/**
	 * 删除工单
	 * 
	 * @param model
	 * @param request
	 * @return
	 */
	@RequestMapping("delShoporder")
	public String delShoporder(Model model, HttpServletRequest request) {
		String shoporderId = request.getParameter("shoporder_id");
		try {
			if (StringUtils.isEmpty(shoporderId)) {
				throw new BusinessException("操作失败，参数不能为空！");
			}
			shoporderMaintenanceService.delShoporder(shoporderId);
		} catch (BusinessException e) {
			String errMessage = e.getMessage();
			log.error(errMessage);
			model.addAttribute("res", findByRes());
			setShoporderStatusList(model);
			setSfcStatusList(model);
			model.addAttribute("dataKeys", getUDefinedDataField(uDefinedDataType));
			model.addAttribute("errorMessage", errMessage);
			handlePageRes(model,request);
			return shoporderMaintenanceUrl;
		}
		model.addAttribute("res", findByRes());
		setShoporderStatusList(model);
		setSfcStatusList(model);
		model.addAttribute("dataKeys", getUDefinedDataField(uDefinedDataType));
		model.addAttribute("successMessage", "删除工单成功");
		handlePageRes(model,request);
		return shoporderMaintenanceUrl;
	}

}